package com.hzcx.app.simplechat.ui.group;

import android.app.Activity;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.TextView;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.google.gson.Gson;
import com.hzcx.app.simplechat.R;
import com.hzcx.app.simplechat.api.BaseDialogObserver;
import com.hzcx.app.simplechat.api.BaseObserver;
import com.hzcx.app.simplechat.base.BaseEmptyBean;
import com.hzcx.app.simplechat.base.BaseLoadingDialog;
import com.hzcx.app.simplechat.chat.ChatUiHelper;
import com.hzcx.app.simplechat.model.GroupModel;
import com.hzcx.app.simplechat.ui.friend.bean.FriendBean;
import com.hzcx.app.simplechat.ui.friend.bean.FriendCityBean;
import com.hzcx.app.simplechat.ui.group.LiveData.GroupInfoBeanLiveData;
import com.hzcx.app.simplechat.ui.group.adapter.GroupMembersSort;
import com.hzcx.app.simplechat.ui.group.bean.GroupInfoBean;
import com.hzcx.app.simplechat.ui.group.bean.MembersBean;
import com.hzcx.app.simplechat.ui.group.bean.QueryMembersBean;
import com.hzcx.app.simplechat.util.log.LogUtils;

import java.util.ArrayList;
import java.util.List;

public class ChatGroupDeleteMemberActivity extends GroupDeleteMemberActivity {

    private EditText etSearch;

    @Override
    public void initView() {
        super.initView();
        tvTitle.setText("移出成员");
        sideBar.setVisibility(View.GONE);
        goneCreateHeader();
        if (this instanceof GroupManagerDeleteActivity){
            return;
        }
        getMembers("",false);
    }

    /**
     * 搜索群成员（单个禁言、添加管理、群主转让）
     */
    public void addGroupHeader() {
        findViewById(R.id.et_search).setVisibility(View.VISIBLE);
        etSearch = findViewById(R.id.et_search);
        etSearch.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                    hideSoftKeyboard();
                    page=1;
                    getMembers(v.getText().toString(),false);
                    return true;

                }
                return false;
            }
        });
        etSearch.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
            }

            @Override
            public void afterTextChanged(Editable editable) {
                page=1;
                if (TextUtils.isEmpty(editable.toString())){
                    getMembers("",false);
                }
            }
        });
    }

    public  void hideSoftKeyboard() {

        View view = getCurrentFocus();

        if (view != null) {

            InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Activity.INPUT_METHOD_SERVICE);

            inputMethodManager.hideSoftInputFromWindow(view.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);

        }

    }
    @Override
    public void loadMore() {
        super.loadMore();
        if (etSearch!=null){
            if (this instanceof GroupManagerDeleteActivity){
                return;
            }
            getMembers(etSearch.getText().toString(),true);
        }
    }

    private void getMembers(String key,boolean isLoadMore) {
        GroupModel.queryGroupMembers(ChatGroupDeleteMemberActivity.this, key, groupID, String.valueOf(page), String.valueOf(pageSize), new BaseDialogObserver<QueryMembersBean>(this) {
            @Override
            protected void onSuccess(QueryMembersBean data) {
                swipeToLoadLayout.setLoadingMore(false);
                List<FriendBean> beans = GroupMembersSort.noSortFriend(data.getData());
                haveMoreData = data.isHas_more();
                if (beans==null||beans.isEmpty()){
                    return;
                }
                page++;
                if (!isLoadMore) {
                    friendData.clear();
                }
                friendData.addAll(beans);
                setDefaultCheckedData();
                friendAdapter.notifyDataSetChanged();

                // 改变右侧字母选项
                List<String> list=new ArrayList<>();
                list.add("↑");
                for (FriendBean bean:friendData){
                    list.add(bean.getName());
                }
                String[] toBeStored = list.toArray(new String[list.size()]);
                sideBar.setContent(toBeStored);
            }

            @Override
            public void onFailure(Throwable e, String errorMsg) {
                super.onFailure(e, errorMsg);
                swipeToLoadLayout.setLoadingMore(false);
            }
        });
    }

    @Override
    public void initData() {
        listData = new ArrayList<>();
        friendData.clear();
        if (this instanceof GroupManagerDeleteActivity){
            Object str = getIntent().getSerializableExtra(INTENT_LIST_BUNDLE);
            Object[] strList = (Object[]) str;
            if (null != strList) {
                for (int i = 0; i < strList.length; i++) {
                    FriendBean bean = (FriendBean) strList[i];
                    friendData.add(bean);
                }
            }

            LogUtils.d(new Gson().toJson(friendData));

            addGroupCreateHeader();

            setDefaultCheckedData();
            friendAdapter.notifyDataSetChanged();

            // 改变右侧字母选项
            List<String> list=new ArrayList<>();
            list.add("↑");
            for (FriendBean bean:friendData){
                list.add(bean.getName());
            }
            String[] toBeStored = list.toArray(new String[list.size()]);
            sideBar.setContent(toBeStored);

        }else {
            addGroupHeader();
        }
    }

    /**
     * 原始成员列表是否已经包含对应的好友
     */
    @Override
    public boolean hasCheck(FriendCityBean bean) {
        return false;
    }

    /**
     * 设置默认选中的好友
     */
    public void setDefaultCheckedData() {
    }

    /**
     * 好友列表获取成功
     *
     * @param data
     */
    @Override
    public void friendListResult(List<FriendBean> data) {
    }

    @Override
    public void finishAction(List<FriendBean> beans) {
        String ids = "";

        List<String> selectID = new ArrayList<>();
        for (FriendBean friend: beans) {
            for (FriendCityBean friendCityBean: friend.getCity()) {
                if (!friendCityBean.isChecked()) {
                    continue;
                }
                selectID.add(String.valueOf(friendCityBean.getMember_id()));
            }
        }

        for (String select: selectID) {
            ids = ids + select + ",";
        }
        if (ids.length() > 1) {
            ids = ids.substring(0, ids.length() - 1);
        }

        Log.i("createGroup", "create group ids : " + ids);

        showLoading();
        deleteMember(ids);
    }

    public void deleteMember(String ids) {
        GroupModel.deleteGroupMember(this, groupID, ids, new BaseObserver<BaseEmptyBean>() {
            @Override
            protected void onSuccess(BaseEmptyBean data) {
                GroupInfoBean groupInfoBean = GroupInfoBeanLiveData.getGroupInfoBean(groupID);
                if (groupInfoBean != null) {
                    List<MembersBean> deletes = new ArrayList<>();
                    String[] idArray = ids.split(",");
                    for (int i = 0; i < idArray.length; i++) {
                       String id = idArray[i];
                        for (MembersBean bean: groupInfoBean.getMembers()) {
                            if (id.equals(String.valueOf(bean.getMember_id()))) {
                                deletes.add(bean);
                            }
                        }
                    }
                   groupInfoBean.getMembers().removeAll(deletes);
                }
                hideLoading();
                finish();
            }

            @Override
            public void onFailure(Throwable e, String errorMsg) {
                hideLoading();
                showError("操作失败，请重试");
            }
        });
    }

}
